<template>
  <view class="upload-container" @click="chooseImage">
    <!-- 已上传图片数量显示 - 固定在右上角 -->
    <view class="image-count-badge" v-if="imageUrls.length > 0">
      <text class="count-text">{{ imageUrls.length }}</text>
    </view>
    
    <!-- 显示已上传的第一张图片作为预览 -->
    <image
      v-if="imageUrls.length > 0"
      :src="imageUrls[0]"
      class="uploaded-image"
      mode="aspectFill"
    ></image>

    <!-- 默认上传状态 -->
    <view v-else class="upload-content">
      <view class="upload-icon">
        <uni-icons type="plus-filled" size="50" color="#42b983"></uni-icons>
      </view>
      <text class="upload-text">{{title}}</text>
    </view>

    <!-- 上传进度条 -->
    <view v-if="showProgress" class="progress-container">
      <view class="progress-bar" :style="{ width: progressPercent + '%' }"></view>
      <text class="progress-text">{{ progressPercent }}%</text>
    </view>
  </view>
</template>

<script>
export default {
  name: 'zmt-upload-images',
  data() {
    return {
      imageUrls: [], // 图片路径数组
      showProgress: false, // 是否显示进度条
      progressPercent: 0, // 上传进度百分比
      currentUploadCount: 0, // 当前正在上传的图片数量
      totalUploadCount: 0 // 本次需要上传的总图片数量
    };
  },
  props:{
	 title:{
		 type:String,
		 default:'请上传产品主图(800px * 800px)'
	 },
	 number:{
		 type:Number,
		 default:10
	 },
	 index:{
		 type:Number,
		 default:null
	 },
	 url:{
		 type:String,
		 default:''
	 }
  },
  watch:{
	"url"(val){
		if(val){
			this.imageUrls[0] = val;
		}
		
	}  
  },
  mounted() {
	var that = this;
	if(this.url && this.url.length > 5){
		setTimeout(function(){
			that.imageUrls[0] = that.url;
		},500);
	}
  
  },
  methods: {
    chooseImage() {
      var that = this;
      uni.chooseImage({
        count: this.number, // 最多选择9张图片
        sizeType: ['compressed'], // 可选压缩图
        sourceType: ['album', 'camera'], // 相册或相机
        success: (res) => {
          that.totalUploadCount = res.tempFilePaths.length;
          that.currentUploadCount = 0;
          
          // 重置并显示进度条
          that.showProgress = true;
          that.progressPercent = 0;
          
          // 上传每张图片
          res.tempFilePaths.forEach((tempFilePath, index) => {
            const tempFile = res.tempFiles[index];
            const fileName = that.generateUUIDFilename(tempFile.name);
            
            uniCloud.uploadFile({
              filePath: tempFilePath,
              cloudPath: fileName,
              onUploadProgress: function(progressEvent) {
                // 计算整体进度
                const singleFilePercent = Math.round(
                  (progressEvent.loaded * 100) / progressEvent.total
                );
                // 计算当前图片在总进度中的占比
                const currentFileContribution = singleFilePercent / that.totalUploadCount;
                // 计算已完成上传的图片贡献的进度
                const completedFilesContribution = (that.currentUploadCount) * 100 / that.totalUploadCount;
                // 总进度 = 已完成图片贡献 + 当前图片贡献
                that.progressPercent = Math.min(
                  Math.round(completedFilesContribution + currentFileContribution),
                  100
                );
              },
              success(uploadRes) {
                // 添加到图片数组
				if(that.number == 1){
					that.imageUrls = [];
				}
                that.imageUrls.push(uploadRes.fileID);
                that.currentUploadCount++;
                
                // 如果所有图片都上传完成
                if (that.currentUploadCount === that.totalUploadCount) {
                  that.$emit('success', {imageUrl:that.imageUrls,index:that.index});
                  // 上传成功后隐藏进度条
                  setTimeout(() => {
                    that.showProgress = false;
                  }, 500);
                }
              },
              fail(err) {
                uni.showToast({
                  title: '图片上传失败',
                  icon: 'none'
                });
                that.currentUploadCount++;
                
                // 如果所有图片都处理完成（无论成功失败）
                if (that.currentUploadCount === that.totalUploadCount) {
                  // 上传失败后隐藏进度条
                  that.showProgress = false;
                  that.progressPercent = 0;
                  that.$emit('fail', {
                    error: err,
                    uploadedImages: that.imageUrls
                  });
                }
              }
            });
          });
        },
        fail: (err) => {
          if (!err.cancelled) {
            uni.showToast({
              title: '选择图片失败',
              icon: 'none'
            });
          }
        }
      });
    },

    uuidv4() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = (Math.random() * 16) | 0;
        const v = c === 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    },
 
    generateUUIDFilename(filename) {
      const ext = filename.substring(filename.lastIndexOf('.'));
      return this.uuidv4() + ext;
    },
    
    // 新增方法：清空已上传图片
    clearImages() {
      this.imageUrls = [];
    },
    
    // 新增方法：删除指定索引的图片
    removeImage(index) {
      if (index >= 0 && index < this.imageUrls.length) {
        this.imageUrls.splice(index, 1);
        this.$emit('change', this.imageUrls);
      }
    }

  }
};
</script>

<style scoped>
.upload-container {
  width: 100%;
  aspect-ratio: 1 / 1; /* 宽高比 1:1，自动计算高度 */
  border: 2rpx dashed #ccc;
  border-radius: 16rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  overflow: hidden;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #888;
  font-size: 28rpx;
  cursor: pointer;
}

.upload-icon {
  font-size: 60rpx;
  margin-bottom: 16rpx;
  color: #1aad19;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  border-radius: 16rpx;
}

/* 进度条样式 */
.progress-container {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 20rpx;
  background-color: rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
}

.progress-bar {
  height: 100%;
  background-color: #1aad19;
  transition: width 0.3s ease;
}

.progress-text {
  position: absolute;
  right: 10rpx;
  font-size: 20rpx;
  color: #333;
  font-weight: bold;
}

/* 图片数量显示 - 右上角徽章 */
.image-count-badge {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: #ff4d4f;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
  z-index: 10;
}

.count-text {
  color: white;
  font-size: 24rpx;
  font-weight: bold;
  line-height: 40rpx;
  text-align: center;
}
</style>
